package com.stn.zjx.givingtreasure.activity.userwallet;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.came.viewbguilib.ButtonBgUi;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.google.gson.Gson;
import com.jungly.gridpasswordview.GridPasswordView;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.set.ForgetPayPassActivity;
import com.stn.zjx.givingtreasure.activity.set.UserPhoneBindActivity;
import com.stn.zjx.givingtreasure.adapter.SelectPayMethodItemListAdapter;
import com.stn.zjx.givingtreasure.adapter.ViewPagerAdpater;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.bean.SelectPayMethod;
import com.stn.zjx.givingtreasure.domain.PayOrderNoResultDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.SelectPayMethodEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.PayNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.widget.NoScrollViewPager;
import com.stn.zjx.givingtreasure.widget.VirtualKeyboardView;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.module.alipay.PayResult;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserRechargeActivity extends BaseActivity {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.skip_bt)
    TextView skipBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.scan_bt)
    RelativeLayout scanBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.search_iv)
    ImageView searchIv;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.search_bg)
    RelativeLayout searchBg;
    @BindView(R.id.save_bt)
    TextView saveBt;
    @BindView(R.id.delete_bt)
    RelativeLayout deleteBt;
    @BindView(R.id.money_edit)
    EditText moneyEdit;
    @BindView(R.id.balance_bt)
    LinearLayout balanceBt;
    @BindView(R.id.next_bt)
    ButtonBgUi nextBt;


    private String subject = "充值余额";
    private String body = "余额充值";
    private String amount = "0";

   private  int  payType=1;
   private String userBankCardName="";
    private String userBankCardNo="";
    private String userBankCardType="";
    TextView  payment_method_tv;

    NoScrollViewPager viewpager;

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                         finish();
                    } else {
                        showToast(payResult.getMemo());
                    }
                    break;
                }



            }
        };
    };

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.recharge));
        nextBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (TextUtils.isEmpty(moneyEdit.getText().toString())) {
                        showToast(getString(R.string.money_is_not_null));
                        return;
                    }
                    if (Double.parseDouble(moneyEdit.getText().toString()) < 0.01) {
                        showToast(getString(R.string.money_not_is_zero));
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(getString(R.string.money_not_is_num));
                    return;
                }
                amount=moneyEdit.getText().toString().trim();

                initSelectDialog();
            }
        });
        moneyEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(moneyEdit.getText().toString().trim())) {
                    nextBt.setAlpha(0.4f);
                    nextBt.setClickable(false);
                    deleteBt.setVisibility(View.GONE);
                } else {
                    nextBt.setAlpha(1.0f);
                    nextBt.setClickable(true);
                    deleteBt.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        deleteBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                moneyEdit.getText().clear();
            }
        });

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_recharge);
        ButterKnife.bind(this);
        initComponent();
    }
  @SuppressLint("SetTextI18n")
  @Subscribe(threadMode = ThreadMode.MAIN)
  public void onSelectPayMethod(SelectPayMethodEvent event){
            switch (event.flag){
                case SelectPayMethodEvent.SELECTFINISH:
                    payType=event.getPayType();
                    userBankCardName=event.getUserBankCardName();
                    userBankCardNo=event.getUserBankCardNo();
                    userBankCardType=event.getUserBankCardType();
                    if(payment_method_tv!=null){
                        switch (payType){
                            case 1:
                                payment_method_tv.setText(getString(R.string.alipay));
                                break;
                            case 2:
                                payment_method_tv.setText(getString(R.string.wechat));
                                break;
                            case 3:
                                if(userBankCardNo.length()>4){
                                    payment_method_tv.setText(userBankCardName+userBankCardType+"("+userBankCardNo.substring(userBankCardNo.length()-4,userBankCardNo.length())+")");
                                }else{
                                    payment_method_tv.setText(userBankCardName+userBankCardType+"("+userBankCardNo+")");
                                }
                                break;
                        }
                    }
                    if(viewpager!=null){
                        viewpager.setCurrentItem(0,true);
                    }
                    break;
            }
  }
    @OnClick({R.id.back_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
        }
    }

    @SuppressLint("SetTextI18n")
    public void initSelectDialog() {
        SoftInputUtils.closedSoftInput(this);
        Dialog select_dialog;
        VirtualKeyboardView virtualKeyboardView;
        GridView gridView;

        select_dialog = new Dialog(this, R.style.dialog_soft_input);
        select_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        select_dialog.setContentView(R.layout.dialog_create_select_order_no);
        WindowManager.LayoutParams lp = select_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        select_dialog.getWindow().setWindowAnimations(R.style.myDialogStyle);  //添加动画
        select_dialog.getWindow().setAttributes(lp);
         viewpager=select_dialog.findViewById(R.id.viewpager);
        ArrayList<View> viewList = new ArrayList<>();


        View select=View.inflate(this,R.layout.dialog_input_confirm_pay,null);
        TextView  money_tv= select.findViewById(R.id.money_tv);
        TextView  subject_tv= select.findViewById(R.id.subject_tv);
          payment_method_tv= select.findViewById(R.id.payment_method_tv);
        RelativeLayout select_close=select.findViewById(R.id.close);
        TextView  input_password_bt= select.findViewById(R.id.input_password_bt);


        View pay=View.inflate(this,R.layout.dialog_input_pay_password,null);
        RelativeLayout pay_close=pay.findViewById(R.id.close);
        TextView pay_forgetpassword_bt = pay.findViewById(R.id.forgetpassword_bt);
        GridPasswordView gridPasswordView;   gridPasswordView = pay.findViewById(R.id.grid_password_edit);
        gridPasswordView.mInputView.setFocusable(false);
        gridPasswordView.mInputView.setFocusableInTouchMode(false);
        virtualKeyboardView = pay.findViewById(R.id.virtualKeyboardView);
        gridView=pay.findViewById(R.id.gv_keybord);

        View select_pay=View.inflate(this,R.layout.dialog_input_select_pay,null);
        RelativeLayout back_bt = select_pay.findViewById(R.id.back_bt);
        RecyclerView rv=select_pay.findViewById(R.id.rv);

         SelectPayMethodItemListAdapter selectAdapter;


        rv.setLayoutManager(new LinearLayoutManager(this,OrientationHelper.VERTICAL,false){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rv.setAdapter(selectAdapter=new SelectPayMethodItemListAdapter(this));
        List<SelectPayMethod> methods=new ArrayList<>();
        SelectPayMethod method1=new SelectPayMethod();
        method1.setPayType(1);
        SelectPayMethod method2=new SelectPayMethod();
        method2.setPayType(2);

        methods.add(method1);
        methods.add(method2);
        selectAdapter.refreshList(methods);

        viewList.add(select);
        viewList.add(pay);
        viewList.add(select_pay);
        viewpager.setOffscreenPageLimit(2);
        viewpager.setAdapter(  new ViewPagerAdpater(viewList));

        DecimalFormat df=new DecimalFormat("0.00");
        money_tv.setText(df.format(Double.parseDouble(amount)));
        subject_tv.setText(subject);
        switch (payType){
               case 1:
                payment_method_tv.setText(getString(R.string.alipay));
                break;
            case 2:
                payment_method_tv.setText(getString(R.string.wechat));
                break;
            case 3:
                if(userBankCardNo.length()>4){
                    payment_method_tv.setText(userBankCardName+userBankCardNo.substring(userBankCardNo.length()-4,userBankCardNo.length()));
                }else{
                    payment_method_tv.setText(userBankCardName+userBankCardNo);
                }
                break;
        }


        input_password_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                viewpager.setCurrentItem(1,true);


            }
        });
        select_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                select_dialog.dismiss();
            }
        });


        pay_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                select_dialog.dismiss();
            }
        });
        pay_forgetpassword_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User user = UserService.getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (user == null) {
                    return;
                }
                if (TextUtils.isEmpty(user.getUserPhone())) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserPhoneBindActivity.class);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("phone", user.getUserPhone());
                    RxActivityTool.skipActivity(getApplicationContext(), ForgetPayPassActivity.class, bundle);
                }
            }
        });



        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (position < 11 && position != 9) {    //点击0~9按钮
                    if(gridPasswordView.getPassWord().length()<6){
                        gridPasswordView.setPassword(gridPasswordView.getPassWord()+virtualKeyboardView.getValueList().get(position).get("name"));
                    }
                    if(gridPasswordView.getPassWord().length()==6){
                        User onlineUser = UserService.getInstance(UserRechargeActivity.this).getOnlineLoginUser();
                        if (onlineUser == null) {
                            return;
                        }
                      select_dialog.dismiss();
                        user_recharge(onlineUser.getToken(),
                                gridPasswordView.getPassWord(),
                                subject,
                                body,
                                amount,
                                payType,
                                userBankCardName,
                                userBankCardNo
                                );
                    }
                } else {
                    if (position == 11) {      //点击退格键
                        if(gridPasswordView.getPassWord().length()>0){
                            gridPasswordView.setPassword(gridPasswordView.getPassWord().substring(0,gridPasswordView.getPassWord().length()-1));
                        }
                    }
                }
            }
        });

        payment_method_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewpager.setCurrentItem(2,true);
            }
        });
        back_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewpager.setCurrentItem(0,true);
            }
        });

        select_dialog.show();


    }


    public void user_recharge(String token ,
                              String userPrivatepwd,
                              String subject,
                                String body,
                                String userMoney,
                                Integer payType,
                                String userBankCardName,
                                String userBankCardNo){
        PayNetImpl
                .user_recharge_create_order_no(token,
                        userPrivatepwd,
                        subject,
                        body,
                        userMoney,
                        payType,
                        userBankCardName,
                        userBankCardNo
                        , token + "_user_recharge_create_order_no", new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                             showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                             dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                PayOrderNoResultDomain domain=new Gson().fromJson(response.body(),PayOrderNoResultDomain.class);
                                   switch (domain.getStatus()){
                                       case BaseApi.REQUEST_SUCCESS_CODE:
                                           switch (domain.getData().getPayType()){
                                               case 0:

                                                   break;
                                               case 1:
                                                   aliPay(domain.getData().getSign());

                                                   break;
                                               case 2:


                                                   break;
                                               case 3:


                                                   break;

                                           }
                                           break;
                                        default:
                                            showToast(domain.getMessage());
                                            break;
                                   }
                            }
                        });
    }


    public void aliPay(String sign){
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                showToast(getString(R.string.loading_alipay_client));
//            }
//        });
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
              PayTask alipay = new PayTask(UserRechargeActivity.this);
                Map<String, String> result = alipay.payV2(sign, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);

            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

}
